package com.test.mylist;

public class IListImpl implements IList {

    public final int initSize = 10;
    public int afterExpandSize = initSize;    
    public int size;
    
    public final float expandParam = 0.75f;
    
    public Object[] elements = new Object[initSize];
    
    public IListImpl() {
    }
    
    @Override
    public void add(Object elem) {
        //计算是否需要扩容
        if(size == afterExpandSize){
            expandElements();
        }
        elements[size] = elem;
        size++;
    }

    private void expandElements() {
        afterExpandSize = (int) (afterExpandSize * expandParam) + afterExpandSize;
        int tempSize = afterExpandSize;
        Object[] tempArr = new Object[tempSize];
        System.arraycopy(elements, 0, tempArr, 0, size);
        elements = tempArr;
    }

    @Override
    public Object get(int index) {
        if (index > size) {
            throw new RuntimeException("下标越界！");
        }
        return elements[index];
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public void clear() {
        for (int i = 0; i < size; i++)
            elements[i] = null;
        size = 0;
    }

}
